/*
*	@file
*	@author  Thomas Kroes <t.kroes at tudelft.nl>
*	@version 1.0
*	
*	@section LICENSE
*	
*	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*	
*	Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*	Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*	Neither the name of the TU Delft nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
*	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*	
*	Part of the SSAO code is based on the tutorial by Michael Belanec: http://www.belanecbn.sk/opengl_tutorialy/index.php?id=30
*	The bloom filter code is based on code snippets from chapter 8 in "iPhone 3D Programming: http://ofps.oreilly.com/titles/9780596804824/chadvanced.html"
*
*/

#pragma once

#include "vtkAmbientOcclusionPass.h"
#include "vtkAmbientOcclusionPassUtilities.h"

#include <vtkObjectFactory.h>
#include <vtkMatrix4x4.h>
#include <assert.h>
#include <vtkRenderState.h>
#include <vtkRenderer.h>
#include <vtkgl.h>
#include <vtkFrameBufferObject.h>
#include <vtkTextureObject.h>
#include <vtkShaderProgram2.h>
#include <vtkShader2.h>
#include <vtkShader2Collection.h>
#include <vtkUniformVariables.h>
#include <vtkOpenGLRenderWindow.h>
#include <vtkTextureUnitManager.h>
#include <vtkImageData.h>
#include <vtkCamera.h>
#include <vtkMath.h>
#include <vtkPixelBufferObject.h>

vtkStandardNewMacro(vtkAmbientOcclusionPass);

vtkAmbientOcclusionPass::vtkAmbientOcclusionPass()
{
	this->FrameBufferObject			= vtkFrameBufferObject::New();
	this->DelegateTexture			= vtkTextureObject::New();
	this->DepthTexture				= vtkTextureObject::New();
	this->NormalTexture				= vtkTextureObject::New();
	this->RandomTexture				= vtkTextureObject::New();
	this->SsaoTexture				= vtkTextureObject::New();
	this->SsaoFilterTexture			= vtkTextureObject::New();
	this->PreprocessShader			= vtkShaderProgram2::New();
	this->SsaoShader				= vtkShaderProgram2::New();
	this->FilterHShader				= vtkShaderProgram2::New();
	this->FilterVShader				= vtkShaderProgram2::New();
	this->CompositingShader			= vtkShaderProgram2::New();
	this->WindowSize[0]				= -1;
	this->WindowSize[1]				= -1;
	this->Supported					= false;
	this->SupportChecked			= false;
	this->RandomSize[0]				= 64;
	this->RandomSize[1]				= 64;
	this->KernelWidth				= 8;

	printf("Loading shaders\n");
	
	this->CreateNormalShader();
	this->CreateSsaoShader();
	this->CreateHorizontalFilterShader();
	this->CreateVerticalFilterShader();
	this->CreateCompositingShader();

	// Default settings
	this->SetBlur(true);
	this->SetRenderMode(Composited);
	this->SetKernelRadius(0.25f);
}

vtkAmbientOcclusionPass::~vtkAmbientOcclusionPass()
{
}

void vtkAmbientOcclusionPass::PrintSelf(ostream& os, vtkIndent indent)
{
	this->Superclass::PrintSelf(os,indent);
}

void vtkAmbientOcclusionPass::UpdateShaders(const vtkRenderState* RenderState)
{
	int CurrentWindowSize[2];
	RenderState->GetWindowSize(CurrentWindowSize);

	// Ssao parameters
	vtkUniformVariables* SsaoShaderUV = this->SsaoShader->GetUniformVariables();

	float Projection[16], InvProjection[16];

	vtkSmartPointer<vtkMatrix4x4> Projection4x4 = vtkMatrix4x4::New();

	Projection4x4 = RenderState->GetRenderer()->GetActiveCamera()->GetProjectionTransformMatrix((float)CurrentWindowSize[0] / (float)CurrentWindowSize[1], -1, 1);//RenderState->GetRenderer()->GetActiveCamera()->GetClippingRange()[0], RenderState->GetRenderer()->GetActiveCamera()->GetClippingRange()[1]);

	Projection4x4->Transpose();

	for (int r = 0; r < 4; r++)
	{
		for (int c = 0; c < 4; c++)
		{
			Projection[r * 4 + c] = Projection4x4->GetElement(r, c);
		}
	}

	Projection4x4 = RenderState->GetRenderer()->GetActiveCamera()->GetProjectionTransformMatrix((float)CurrentWindowSize[0] / (float)CurrentWindowSize[1], -1, 1);//RenderState->GetRenderer()->GetActiveCamera()->GetClippingRange()[0], RenderState->GetRenderer()->GetActiveCamera()->GetClippingRange()[1]);

	Projection4x4->Invert();
	Projection4x4->Transpose();

	for (int r = 0; r < 4; r++)
	{
		for (int c = 0; c < 4; c++)
		{
			InvProjection[r * 4 + c] = Projection4x4->GetElement(r, c);
		}
	}

	SsaoShaderUV->SetUniformMatrix("Projection", 4, 4, &Projection[0]);
	SsaoShaderUV->SetUniformMatrix("ProjectionInverse", 4, 4, &InvProjection[0]);
	
	float ScreenSize[2]		= { (float)CurrentWindowSize[0], (float)CurrentWindowSize[1] };
	float InvScreenSize[2]	= { 1.0f / (float)CurrentWindowSize[0], 1.0f / (float)CurrentWindowSize[1] };
	
	this->SsaoShader->GetUniformVariables()->SetUniformfv("ScreenSize", 2, 1, ScreenSize);
	this->SsaoShader->GetUniformVariables()->SetUniformfv("InvScreenSize", 2, 1, InvScreenSize);

	this->SsaoShader->Build();

	float Sx = 1.0f / (float)CurrentWindowSize[0];
	float Sy = 1.0f / (float)CurrentWindowSize[1];

	// Horizontal filter parameters
	vtkUniformVariables* HorizontalFilterShaderUV = this->FilterHShader->GetUniformVariables();
	HorizontalFilterShaderUV->SetUniformf("Sx", 1, &Sx);
	this->FilterHShader->Build();
	
	// Vertical filter parameters
	vtkUniformVariables* VerticalFilterShaderUV = this->FilterVShader->GetUniformVariables();
	VerticalFilterShaderUV->SetUniformf("Sy", 1, &Sy);
	this->FilterVShader->Build();
	
	this->CompositingShader->Build();
}

void vtkAmbientOcclusionPass::PreRender(const vtkRenderState* RenderState)
{
	int CurrentWindowSize[2];
	RenderState->GetWindowSize(CurrentWindowSize);

	if (CurrentWindowSize[0] == this->WindowSize[0] && CurrentWindowSize[1] == this->WindowSize[1])
		return;

	vtkOpenGLRenderWindow* RenderWindow = (vtkOpenGLRenderWindow*)RenderState->GetRenderer()->GetRenderWindow();

	// Update render texture
	this->DelegateTexture->SetContext(RenderWindow);
	this->DelegateTexture->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 4, VTK_UNSIGNED_CHAR, false);
	this->DelegateTexture->SetMinificationFilter(vtkTextureObject::Nearest);
	this->DelegateTexture->SetLinearMagnification(false);
	this->DelegateTexture->SetWrapS(vtkTextureObject::Clamp);
	this->DelegateTexture->SetWrapT(vtkTextureObject::Clamp);

	// Update depth texture
	this->DepthTexture->SetContext(RenderWindow);
	this->DepthTexture->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 1, VTK_VOID, false);
	this->DepthTexture->SetMinificationFilter(vtkTextureObject::Nearest);
	this->DepthTexture->SetLinearMagnification(false);
	this->DepthTexture->SetWrapS(vtkTextureObject::Clamp);
	this->DepthTexture->SetWrapT(vtkTextureObject::Clamp);

	// Update normal texture
	this->NormalTexture->SetContext(RenderWindow);
	this->NormalTexture->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 4, VTK_FLOAT, false);
	this->NormalTexture->SetMinificationFilter(vtkTextureObject::Nearest);
	this->NormalTexture->SetLinearMagnification(false);
	this->NormalTexture->SetWrapS(vtkTextureObject::Clamp);
	this->NormalTexture->SetWrapT(vtkTextureObject::Clamp);

	// Update SSAO texture
	this->SsaoTexture->SetContext(RenderWindow);
	this->SsaoTexture->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 4, VTK_UNSIGNED_CHAR, false);
	this->SsaoTexture->SetMinificationFilter(vtkTextureObject::Nearest);
	this->SsaoTexture->SetLinearMagnification(false);
	this->SsaoTexture->SetWrapS(vtkTextureObject::Clamp);
	this->SsaoTexture->SetWrapT(vtkTextureObject::Clamp);

	// Update SSAO texture
	this->SsaoFilterTexture->SetContext(RenderWindow);
	this->SsaoFilterTexture->Create2D(CurrentWindowSize[0], CurrentWindowSize[1], 4, VTK_UNSIGNED_CHAR, false);
	this->SsaoFilterTexture->SetMinificationFilter(vtkTextureObject::Nearest);
	this->SsaoFilterTexture->SetLinearMagnification(false);
	this->SsaoFilterTexture->SetWrapS(vtkTextureObject::Clamp);
	this->SsaoFilterTexture->SetWrapT(vtkTextureObject::Clamp);

	for (int i = 0; i < 2; i++)
		this->WindowSize[i] = CurrentWindowSize[i];
}

void vtkAmbientOcclusionPass::Render(const vtkRenderState* RenderState)
{
	if (!this->Enabled)
	{
		this->GetDelegatePass()->Render(RenderState);
		return;
	}

	if (this->GetDelegatePass() == NULL)
		return;

	this->PreRender(RenderState);

	if (!this->Initialize(RenderState))
	{
		this->DelegatePass->Render(RenderState);
		this->NumberOfRenderedProps += this->DelegatePass->GetNumberOfRenderedProps();
		return;
	}
	
	this->UpdateShaders(RenderState);

	this->FrameBufferObject->SetDepthBufferNeeded(true);
	this->FrameBufferObject->SetNumberOfRenderTargets(2);
	this->FrameBufferObject->SetColorBuffer(0, this->DelegateTexture);
	this->FrameBufferObject->SetColorBuffer(1, this->NormalTexture);
	this->FrameBufferObject->SetDepthBuffer(this->DepthTexture);
	this->FrameBufferObject->SetActiveBuffer(1);
	this->FrameBufferObject->StartNonOrtho(this->WindowSize[0], this->WindowSize[1], false);

	this->RenderDelegate(RenderState, this->WindowSize[0], this->WindowSize[1], this->WindowSize[0], this->WindowSize[1], this->FrameBufferObject, this->DelegateTexture);
	
	this->PreprocessShader->Use();
	this->RenderDelegate(RenderState, this->WindowSize[0], this->WindowSize[1], this->WindowSize[0], this->WindowSize[1], this->FrameBufferObject, this->NormalTexture);
	this->PreprocessShader->Restore();

	this->FrameBufferObject->SetDepthBufferNeeded(false);

	this->ComputeSsao(RenderState);

	if (this->Blur)
//		this->BilateralFilterSsao(RenderState);
		this->GaussianFilterSsao(RenderState);

	this->CompositeSsao(RenderState);
}

void vtkAmbientOcclusionPass::ComputeSsao(const vtkRenderState* RenderState)
{
	vtkTextureUnitManager* TextureUnitManager = static_cast<vtkOpenGLRenderWindow *>(RenderState->GetRenderer()->GetRenderWindow())->GetTextureUnitManager();

	this->FrameBufferObject->RemoveAllColorBuffers();
	this->FrameBufferObject->SetColorBuffer(0, this->SsaoTexture);
	this->FrameBufferObject->SetActiveBuffer(0);
	this->FrameBufferObject->StartNonOrtho(this->WindowSize[0], this->WindowSize[1], false);

	vtkUniformVariables* SsaoShaderUV = this->SsaoShader->GetUniformVariables();

	int DepthTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + DepthTextureID);
	this->DepthTexture->Bind();

	int NormalTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + NormalTextureID);
	this->NormalTexture->Bind();

	int RandomTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + RandomTextureID);
	this->RandomTexture->Bind();

	SsaoShaderUV->SetUniformi("DepthTexture", 1, &DepthTextureID);
	SsaoShaderUV->SetUniformi("NormalTexture", 1, &NormalTextureID);
	SsaoShaderUV->SetUniformi("RandomTexture", 1, &RandomTextureID);

	glDisable(GL_ALPHA_TEST);
	glDisable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);
	glDisable(GL_SCISSOR_TEST);

	this->SsaoShader->Use();

	glBegin(GL_QUADS);
		glVertex2f(0.0f, 0.0f);
		glVertex2f(1.0f, 0.0f);
		glVertex2f(1.0f, 1.0f);
		glVertex2f(0.0f, 1.0f);
	glEnd();

	this->SsaoShader->Restore();

	this->RandomTexture->UnBind();
	this->NormalTexture->UnBind();
	this->DepthTexture->UnBind();

	TextureUnitManager->Free(RandomTextureID);
	TextureUnitManager->Free(NormalTextureID);
	TextureUnitManager->Free(DepthTextureID);
}

void vtkAmbientOcclusionPass::GaussianFilterSsao(const vtkRenderState* RenderState)
{
	vtkTextureUnitManager* TextureUnitManager = static_cast<vtkOpenGLRenderWindow *>(RenderState->GetRenderer()->GetRenderWindow())->GetTextureUnitManager();

	this->FrameBufferObject->SetColorBuffer(0, this->SsaoFilterTexture);
	this->FrameBufferObject->SetActiveBuffer(0);
	this->FrameBufferObject->StartNonOrtho(this->WindowSize[0], this->WindowSize[1], false);

	int SsaoTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + SsaoTextureID);
	this->SsaoTexture->Bind();

	this->FilterHShader->GetUniformVariables()->SetUniformi("SsaoTexture", 1, &SsaoTextureID);

	this->FilterHShader->Use();

	glBegin(GL_QUADS);
		glVertex2f(0.0f, 0.0f);
		glVertex2f(1.0f, 0.0f);
		glVertex2f(1.0f, 1.0f);
		glVertex2f(0.0f, 1.0f);
	glEnd();

	this->FilterHShader->Restore();

	TextureUnitManager->Free(SsaoTextureID);

	this->SsaoTexture->UnBind();

	this->FrameBufferObject->SetColorBuffer(0, this->SsaoTexture);
	this->FrameBufferObject->SetActiveBuffer(0);
	this->FrameBufferObject->StartNonOrtho(this->WindowSize[0], this->WindowSize[1], false);

	int SsaoFilterTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + SsaoFilterTextureID);
	this->SsaoFilterTexture->Bind();

	this->FilterVShader->GetUniformVariables()->SetUniformi("SsaoTexture", 1, &SsaoFilterTextureID);

	this->FilterVShader->Use();

	glBegin(GL_QUADS);
		glVertex2f(0.0f, 0.0f);
		glVertex2f(1.0f, 0.0f);
		glVertex2f(1.0f, 1.0f);
		glVertex2f(0.0f, 1.0f);
	glEnd();

	this->FilterVShader->Restore();

	this->SsaoFilterTexture->UnBind();

	TextureUnitManager->Free(SsaoFilterTextureID);
}

void vtkAmbientOcclusionPass::CompositeSsao(const vtkRenderState* RenderState)
{
	this->FrameBufferObject->UnBind();

	vtkTextureUnitManager* TextureUnitManager = static_cast<vtkOpenGLRenderWindow *>(RenderState->GetRenderer()->GetRenderWindow())->GetTextureUnitManager();
	
	vtkUniformVariables* CompositingUV = this->CompositingShader->GetUniformVariables();

	int DelegateTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + DelegateTextureID);
	this->DelegateTexture->Bind();

	int DepthTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + DepthTextureID);
	this->DepthTexture->Bind();

	int NormalTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + NormalTextureID);
	this->NormalTexture->Bind();

	int SsaoTextureID = TextureUnitManager->Allocate();
	vtkgl::ActiveTexture(vtkgl::TEXTURE0 + SsaoTextureID);
	this->SsaoTexture->Bind();
	
	CompositingUV->SetUniformi("DelegateTexture", 1, &DelegateTextureID);
 	CompositingUV->SetUniformi("DepthTexture", 1, &DepthTextureID);
 	CompositingUV->SetUniformi("NormalTexture", 1, &NormalTextureID);
 	CompositingUV->SetUniformi("SsaoTexture", 1, &SsaoTextureID);

	this->CompositingShader->Use();
	
	glBegin(GL_QUADS);
		glVertex2f(-1.0f, -1.0f);
		glVertex2f(1.0f, -1.0f);
		glVertex2f(1.0f, 1.0f);
		glVertex2f(-1.0f, 1.0f);
	glEnd();

	this->CompositingShader->Restore();
	
	this->SsaoTexture->UnBind();
	this->NormalTexture->UnBind();
	this->DepthTexture->UnBind();
	this->DelegateTexture->UnBind();

	TextureUnitManager->Free(DelegateTextureID);
 	TextureUnitManager->Free(DepthTextureID);
 	TextureUnitManager->Free(NormalTextureID);
 	TextureUnitManager->Free(SsaoTextureID);
}

void vtkAmbientOcclusionPass::ReleaseGraphicsResources(vtkWindow* Window)
{
}

void vtkAmbientOcclusionPass::CreateNormalShader()
{
	printf("Loading pre-processing shader\n");

	// Create vertex and fragment shaders
	vtkSmartPointer<vtkShader2> NormalVS = vtkShader2::New();
	vtkSmartPointer<vtkShader2> NormalFS = vtkShader2::New();

	NormalVS->SetType(VTK_SHADER_TYPE_VERTEX);
	NormalFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	std::ifstream VS("C://Workspaces//vtkambientocclusionpass//source//shaders//preprocess.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	NormalVS->SetSourceCode(StrVS.c_str());

	std::ifstream FS("C://Workspaces//vtkambientocclusionpass//source//shaders//preprocess.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	NormalFS->SetSourceCode(StrFS.c_str());

	NormalVS->SetContext(this->PreprocessShader->GetContext());
	NormalFS->SetContext(this->PreprocessShader->GetContext());

	this->PreprocessShader->GetShaders()->AddItem(NormalFS);
	this->PreprocessShader->GetShaders()->AddItem(NormalVS);
}

void vtkAmbientOcclusionPass::CreateSsaoShader()
{
	printf("Loading SSAO shader\n");

	vtkSmartPointer<vtkShader2> SSAOVS = vtkShader2::New();
	vtkSmartPointer<vtkShader2> SSAOFS = vtkShader2::New();

	SSAOVS->SetType(VTK_SHADER_TYPE_VERTEX);
	SSAOFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	std::ifstream VS("C://Workspaces//vtkambientocclusionpass//source//shaders//ssao.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	SSAOVS->SetSourceCode(StrVS.c_str());

	std::ifstream FS("C://Workspaces//vtkambientocclusionpass//source//shaders//ssao.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	SSAOFS->SetSourceCode(StrFS.c_str());

	SSAOVS->SetContext(this->SsaoShader->GetContext());
	SSAOFS->SetContext(this->SsaoShader->GetContext());

	this->SsaoShader->GetShaders()->AddItem(SSAOVS);
	this->SsaoShader->GetShaders()->AddItem(SSAOFS);
}

void vtkAmbientOcclusionPass::CreateHorizontalFilterShader()
{
	printf("Loading horizontal filter shader\n");

	vtkSmartPointer<vtkShader2> FilterVS			= vtkShader2::New();
	vtkSmartPointer<vtkShader2> HorizontalFilterFS	= vtkShader2::New();

	FilterVS->SetType(VTK_SHADER_TYPE_VERTEX);
	HorizontalFilterFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	std::ifstream VS("C://Workspaces//vtkambientocclusionpass//source//shaders//filter.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	FilterVS->SetSourceCode(StrVS.c_str());

	std::ifstream FS("C://Workspaces//vtkambientocclusionpass//source//shaders//filterh.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	HorizontalFilterFS->SetSourceCode(StrFS.c_str());

	FilterVS->SetContext(this->SsaoShader->GetContext());
	HorizontalFilterFS->SetContext(this->SsaoShader->GetContext());

	this->FilterHShader->GetShaders()->AddItem(FilterVS);
	this->FilterHShader->GetShaders()->AddItem(HorizontalFilterFS);
}

void vtkAmbientOcclusionPass::CreateVerticalFilterShader()
{
	printf("Loading vertical filter shader\n");

	vtkSmartPointer<vtkShader2> FilterVS			= vtkShader2::New();
	vtkSmartPointer<vtkShader2> VerticalFilterFS	= vtkShader2::New();

	FilterVS->SetType(VTK_SHADER_TYPE_VERTEX);
	VerticalFilterFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	std::ifstream VS("C://Workspaces//vtkambientocclusionpass//source//shaders//filter.vs");
	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
	FilterVS->SetSourceCode(StrVS.c_str());

	std::ifstream FS("C://Workspaces//vtkambientocclusionpass//source//shaders//filterv.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	VerticalFilterFS->SetSourceCode(StrFS.c_str());

	FilterVS->SetContext(this->SsaoShader->GetContext());
	VerticalFilterFS->SetContext(this->SsaoShader->GetContext());

	this->FilterVShader->GetShaders()->AddItem(FilterVS);
	this->FilterVShader->GetShaders()->AddItem(VerticalFilterFS);
}

void vtkAmbientOcclusionPass::CreateCompositingShader()
{
	printf("Loading compositing shader\n");

	vtkSmartPointer<vtkShader2> CompositingFS = vtkShader2::New();
	vtkSmartPointer<vtkShader2> CompositingVS = vtkShader2::New();

	CompositingVS->SetType(VTK_SHADER_TYPE_VERTEX);
	CompositingFS->SetType(VTK_SHADER_TYPE_FRAGMENT);

	std::ifstream FS("C://Workspaces//vtkambientocclusionpass//source//shaders//composite.fs");
	std::string StrFS((std::istreambuf_iterator<char>(FS)), std::istreambuf_iterator<char>());
	CompositingFS->SetSourceCode(StrFS.c_str());
	CompositingFS->SetContext(this->CompositingShader->GetContext());

 	std::ifstream VS("C://Workspaces//vtkambientocclusionpass//source//shaders//composite.vs");
 	std::string StrVS((std::istreambuf_iterator<char>(VS)), std::istreambuf_iterator<char>());
 	CompositingVS->SetSourceCode(StrVS.c_str());
 	CompositingVS->SetContext(this->CompositingShader->GetContext());

	this->CompositingShader->GetShaders()->AddItem(CompositingVS);
	this->CompositingShader->GetShaders()->AddItem(CompositingFS);
}

bool vtkAmbientOcclusionPass::Initialize(const vtkRenderState* RenderState)
{
	if (this->GetDelegatePass() == NULL)
		return false;

	if (!this->SupportChecked)
	{
		vtkOpenGLRenderWindow* RenderWindow = (vtkOpenGLRenderWindow*)RenderState->GetRenderer()->GetRenderWindow();

		bool LocalSupported = vtkFrameBufferObject::IsSupported(RenderWindow);

		if (!LocalSupported)
			vtkErrorMacro("FBOs are not supported by the context. Cannot blur the image.");

		if (LocalSupported)
		{
			LocalSupported = vtkTextureObject::IsSupported(RenderWindow);

			if (!LocalSupported)
				vtkErrorMacro("Texture Objects are not supported by the context. Cannot blur the image.");
		}

		if (LocalSupported)
		{
			LocalSupported = vtkShaderProgram2::IsSupported(RenderWindow);

			if (!LocalSupported)
				vtkErrorMacro("GLSL is not supported by the context. Cannot blur the image.");
		}

		if (LocalSupported)
		{
			this->FrameBufferObject->SetContext(RenderWindow);
			this->PreprocessShader->SetContext(RenderWindow);
			this->SsaoShader->SetContext(RenderWindow);
			this->FilterHShader->SetContext(RenderWindow);
			this->FilterVShader->SetContext(RenderWindow);
			this->CompositingShader->SetContext(RenderWindow);

			GLint savedCurrentDrawBuffer;
			glGetIntegerv(GL_DRAW_BUFFER,&savedCurrentDrawBuffer);

			LocalSupported = this->FrameBufferObject->StartNonOrtho(this->WindowSize[0], this->WindowSize[1], false);

			if (!LocalSupported)
			{
				vtkErrorMacro("The requested FBO format is not supported by the context. Cannot blur the image.");
			}
			else
			{
				this->FrameBufferObject->UnBind();
				glDrawBuffer(static_cast<GLenum>(savedCurrentDrawBuffer));
			}
		}

		this->Supported			= LocalSupported;
		this->SupportChecked	= true;

		this->CreateRandomUnitVectors(RenderState);	
		this->CreateSampleVectors(RenderState);
	}

	return this->Supported;
}

void vtkAmbientOcclusionPass::SetRenderMode(int RenderMode)
{
	this->RenderMode = RenderMode;
	this->CompositingShader->GetUniformVariables()->SetUniformi("RenderMode", 1, &this->RenderMode);
}

void vtkAmbientOcclusionPass::SetKernelRadius(float KernelRadius)
{
	this->KernelRadius = KernelRadius;
	this->SsaoShader->GetUniformVariables()->SetUniformf("KernelRadius", 1, &this->KernelRadius);
}

void vtkAmbientOcclusionPass::CreateRandomUnitVectors(const vtkRenderState* RenderState)
{
	vtkOpenGLRenderWindow* RenderWindow = (vtkOpenGLRenderWindow*)RenderState->GetRenderer()->GetRenderWindow();

	const int NoRandomVectors = this->RandomSize[0] * this->RandomSize[1];

	float* RandomUnitVectors = new float[NoRandomVectors * 3];

	for (int i = 0; i < NoRandomVectors; i++)
	{
		float RandomUnitVector[3] = { -1.0f + 2.0f * Rand1(), -1.0f + 2.0f * Rand1(), -1.0f + 2.0f * Rand1() };

		vtkMath::Normalize(RandomUnitVector);

		for (int c = 0; c < 3; c++)
			RandomUnitVectors[i * 3 + c] = 0.5f + 0.5f * RandomUnitVector[c];
	}

	vtkSmartPointer<vtkPixelBufferObject> PBO = vtkPixelBufferObject::New();

	unsigned int Dimensions[2] = { RandomSize[0], RandomSize[1] };
	int Increments[2] = { 0, 0 };

	PBO->SetContext(RenderWindow);
	PBO->Upload2D(VTK_FLOAT, RandomUnitVectors, Dimensions, 3, Increments);
	
	this->RandomTexture->SetContext(RenderWindow);
	this->RandomTexture->Create2D(RandomSize[0], RandomSize[1], 3, PBO, false);
	this->RandomTexture->SetMinificationFilter(vtkTextureObject::Nearest);
	this->RandomTexture->SetLinearMagnification(false);
	this->RandomTexture->SetWrapS(vtkTextureObject::Repeat);
	this->RandomTexture->SetWrapT(vtkTextureObject::Repeat);

	float RandomSize[2]		= { (float)this->RandomSize[0], (float)this->RandomSize[1] };
	float InvRandomSize[2]	= { 1.0f / (float)this->RandomSize[0], 1.0f / (float)this->RandomSize[1] };
	
	this->SsaoShader->GetUniformVariables()->SetUniformfv("RandomSize", 2, 1, RandomSize);
	this->SsaoShader->GetUniformVariables()->SetUniformfv("InvRandomSize", 2, 1, InvRandomSize);
}

void vtkAmbientOcclusionPass::CreateSampleVectors(const vtkRenderState* RenderState)
{
	int KernelSize = this->KernelWidth * this->KernelWidth;
	float InvKernelSize = 1.0f / (float)KernelSize;

	float* KernelSamples = new float[KernelSize * 3];

	for (int i = 0; i < KernelSize; i++)
	{
		const float Radius = powf(Rand1(), 2.0f);

		float Sample[3] = { -1.0f + 2.0f * Rand1(), -1.0f + 2.0f * Rand1(), -1.0f + 2.0f * Rand1() };
		
 		if (Sample[2] < 0.0f)
 			Sample[2] *= -1.0f;

		vtkMath::Normalize(Sample);

		for (int c = 0; c < 3; c++)
		{
			Sample[c] *= 0.1 + Radius;
			KernelSamples[i * 3 + c] = Sample[c];
			//KernelSamples[i * 3 + c] *= (0.1f * this->KernelRadius) + powf(((float)rand() / (float)RAND_MAX), 2.0f) * this->KernelRadius;
		}
	}

	this->SsaoShader->GetUniformVariables()->SetUniformfv("KernelSamples", 3, 64, (GLfloat*)KernelSamples);
	this->SsaoShader->GetUniformVariables()->SetUniformi("KernelSize", 1, &KernelSize);
	this->SsaoShader->GetUniformVariables()->SetUniformf("InvKernelSize", 1, &InvKernelSize);

	delete[] KernelSamples;
}

